// 客户管理API服务
import axios from 'axios'
import { getCustomerApiUrl } from '@/config/apiConfig'
import { getErrorMessage } from '@/utils/error'
import type {
  CreateCustomerCommand,
  UpdateCustomerCommand,
  DeleteCustomerCommand,
  GetCustomerListQuery,
  GetCustomerByIdQuery,
  CustomerListResponse,
  CustomerDetailResponse,
  OperationResultResponse,
  CreateCustomerResponse
} from '@/types/customer'

// 创建axios实例
const customerApiClient = axios.create({
  baseURL: getCustomerApiUrl(),
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json'
  }
})

// 请求拦截器
customerApiClient.interceptors.request.use(
  (config) => {
    // 可以在这里添加认证token等
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

// 响应拦截器
customerApiClient.interceptors.response.use(
  (response) => {
    return response.data
  },
  (error) => {
    console.error('API请求错误:', error)
    if (error.response) {
      // 服务器返回错误状态码
      const { status, data } = error.response
      switch (status) {
        case 400:
          throw new Error(data?.message || '请求参数错误')
        case 401:
          throw new Error('未授权，请重新登录')
        case 403:
          throw new Error('禁止访问')
        case 404:
          throw new Error('请求的资源不存在')
        case 500:
          throw new Error(data?.message || '服务器内部错误')
        default:
          throw new Error(data?.message || `请求失败 (${status})`)
      }
    } else if (error.request) {
      // 请求已发出但没有收到响应
      throw new Error('网络连接失败，请检查网络设置')
    } else {
      // 请求配置错误
      throw new Error('请求配置错误')
    }
  }
)

function normalizeApiResult<T>(raw: any): { code: number; message: string; data: T } {
  // 注意：拦截器已将 axios 的 response.data 返回给我们，这里不要再取 raw.data
  const outer = raw
  return {
    code: outer?.code ?? outer?.Code ?? 500,
    message: outer?.message ?? outer?.Message ?? '',
    data: (outer?.data ?? outer?.Data) as T
  }
}

// 客户管理API
export const customerApi = {
  /**
   * 获取客户列表
   * @param params 查询参数
   * @returns 客户列表响应
   */
  async getCustomerList(params: GetCustomerListQuery): Promise<CustomerListResponse> {
    try {
      // 后端路由为 /api/Customer/list
      const query = {
        PageIndex: (params as any).PageIndex ?? params.pageIndex,
        PageSize: (params as any).PageSize ?? params.pageSize
      }
      const raw = await customerApiClient.get('/api/Customer/list', { params: query })
      // 规范化大小写与字段，确保 data.pageData 存在
      const normalizedOuter = normalizeApiResult<any>(raw)
      const inner = normalizedOuter.data || {}
      // 有些后端只把数据放在 data 而不是 pageData，这里优先使用非空的 pageData，否则回退到 data
      const candidatePageData = inner.pageData ?? inner.PageData
      const pageData = Array.isArray(candidatePageData) && candidatePageData.length > 0
        ? candidatePageData
        : (inner.data ?? inner.Data ?? [])
      const totalCount = inner.totalCount ?? inner.TotalCount ?? 0
      const pageIndex = inner.pageIndex ?? inner.PageIndex ?? query.PageIndex
      const pageSize = inner.pageSize ?? inner.PageSize ?? query.PageSize
      const totalPages = inner.totalPages ?? inner.TotalPages ?? inner.pageCount ?? inner.PageCount ?? Math.ceil(totalCount / (pageSize || 1))
      return {
        code: normalizedOuter.code,
        message: normalizedOuter.message,
        data: {
          data: pageData,
          pageData: pageData,
          totalCount,
          pageIndex,
          pageSize,
          totalPages
        }
      } as unknown as CustomerListResponse
    } catch (error: unknown) {
      throw new Error(`获取客户列表失败: ${getErrorMessage(error)}`)
    }
  },

  /**
   * 根据ID获取客户详情
   * @param id 客户ID
   * @returns 客户详情响应
   */
  async getCustomerById(id: number): Promise<CustomerDetailResponse> {
    try {
      const raw = await customerApiClient.get(`/api/Customer/${id}`)
      const normalized = normalizeApiResult<any>(raw)
      return {
        code: normalized.code,
        message: normalized.message,
        data: normalized.data
      } as CustomerDetailResponse
    } catch (error: unknown) {
      throw new Error(`获取客户详情失败: ${getErrorMessage(error)}`)
    }
  },

  /**
   * 新增客户
   * @param data 客户数据
   * @returns 新增结果响应
   */
  async createCustomer(data: CreateCustomerCommand): Promise<CreateCustomerResponse> {
    try {
      // 字段映射与类型修正 - 确保与后端CreateCustomerCommand字段名完全匹配
      const payload: any = {
        customerName: data.customerName,
        companyName: data.companyName,
        customerLevelId: (data as any).customerLevelId ?? (data as any).partnerLevelId ?? undefined,
        customerCategoryId: (data as any).customerCategoryId ?? (data as any).partnerCategoryId ?? undefined,
        customerType: data.customerType === 'Individual' ? 1 : data.customerType === 'Enterprise' ? 2 : 2, // 转换为后端枚举值
        customerStatus: data.customerStatus === 'Active' ? 1 : data.customerStatus === 'Inactive' ? 2 : data.customerStatus === 'Blacklisted' ? 3 : 1, // 转换为后端枚举值
        salesRepresentativeId: data.salesRepresentativeId,
        customerSource: data.customerSource,
        creditLimit: data.creditLimit,
        creditRating: data.creditRating,
        paymentTerms: typeof (data as any).paymentTerms === 'string' ? (parseInt((data as any).paymentTerms, 10) || null) : (data as any).paymentTerms,
        personnelScaleId: (data as any).personnelScaleId,
        companyAddressId: (data as any).companyAddressId,
        registeredAddress: (data as any).registeredAddress,
        unifiedSocialCreditCode: (data as any).unifiedSocialCreditCode,
        businessNatureId: (data as any).businessNatureId ?? 1, // 设置默认值，避免必需字段缺失
        industryId: data.industryId,
        registeredCapital: (data as any).registeredCapital,
        locationId: data.locationId,
        remarks: data.remarks,
        IsEnabled: data.isEnabled ?? true // 确保有默认值，使用大写字段名
      }

      console.log('发送客户数据:', JSON.stringify(payload, null, 2)) // 调试日志
      const raw = await customerApiClient.post('/api/Customer', payload)
      const normalized = normalizeApiResult<any>(raw)
      return {
        code: normalized.code,
        message: normalized.message,
        data: normalized.data
      } as CreateCustomerResponse
    } catch (error: unknown) {
      throw new Error(`新增客户失败: ${getErrorMessage(error)}`)
    }
  },

  /**
   * 更新客户
   * @param data 客户数据
   * @returns 更新结果响应
   */
  async updateCustomer(data: UpdateCustomerCommand): Promise<OperationResultResponse> {
    try {
      // 字段映射与类型修正 - 确保与后端UpdateCustomerCommand字段名完全匹配
      const payload: any = {
        id: data.id,
        customerName: data.customerName,
        companyName: data.companyName,
        customerLevelId: (data as any).customerLevelId ?? (data as any).partnerLevelId ?? undefined,
        customerCategoryId: (data as any).customerCategoryId ?? (data as any).partnerCategoryId ?? undefined,
        customerType: data.customerType === 'Individual' ? 1 : data.customerType === 'Enterprise' ? 2 : 2, // 转换为后端枚举值
        customerStatus: data.customerStatus === 'Active' ? 1 : data.customerStatus === 'Inactive' ? 2 : data.customerStatus === 'Blacklisted' ? 3 : 1, // 转换为后端枚举值
        salesRepresentativeId: data.salesRepresentativeId,
        customerSource: data.customerSource,
        creditLimit: data.creditLimit,
        creditRating: data.creditRating,
        paymentTerms: typeof (data as any).paymentTerms === 'string' ? (parseInt((data as any).paymentTerms, 10) || null) : (data as any).paymentTerms,
        personnelScaleId: (data as any).personnelScaleId,
        companyAddressId: (data as any).companyAddressId,
        registeredAddress: (data as any).registeredAddress,
        unifiedSocialCreditCode: (data as any).unifiedSocialCreditCode,
        businessNatureId: (data as any).businessNatureId ?? 1, // 设置默认值，避免必需字段缺失
        industryId: data.industryId,
        registeredCapital: (data as any).registeredCapital,
        locationId: data.locationId,
        remarks: data.remarks,
        IsEnabled: data.isEnabled ?? true // 确保有默认值，使用大写字段名
      }

      // 后端为 [HttpPut] /api/Customer（不带 id 路由）
      const raw = await customerApiClient.put(`/api/Customer`, payload)
      const normalized = normalizeApiResult<any>(raw)
      return {
        code: normalized.code,
        message: normalized.message,
        data: normalized.data
      } as OperationResultResponse
    } catch (error: unknown) {
      throw new Error(`更新客户失败: ${getErrorMessage(error)}`)
    }
  },

  /**
   * 删除客户
   * @param id 客户ID
   * @returns 删除结果响应
   */
  async deleteCustomer(id: number): Promise<OperationResultResponse> {
    try {
      // 后端为 [HttpDelete] /api/Customer，参数在 Body 中
      const raw = await customerApiClient.delete(`/api/Customer`, { data: { id } })
      const normalized = normalizeApiResult<any>(raw)
      return {
        code: normalized.code,
        message: normalized.message,
        data: normalized.data
      } as OperationResultResponse
    } catch (error: unknown) {
      throw new Error(`删除客户失败: ${getErrorMessage(error)}`)
    }
  },

  /**
   * 检查客户编号是否存在
   * @param customerNumber 客户编号
   * @param excludeId 排除的客户ID（用于编辑时检查）
   * @returns 是否存在
   */
  async checkCustomerNumberExists(customerNumber: string, excludeId?: number): Promise<boolean> {
    try {
      const params = excludeId ? { excludeId } : {}
      const response = await customerApiClient.get(`/api/Customer/check-number/${customerNumber}`, { params })
      // 兼容布尔值
      const normalized = normalizeApiResult<any>(response)
      return (normalized.data as any) === true || response?.data === true
    } catch (error: unknown) {
      throw new Error(`检查客户编号失败: ${getErrorMessage(error)}`)
    }
  },

  /**
   * 检查客户名称是否存在
   * @param customerName 客户名称
   * @param excludeId 排除的客户ID（用于编辑时检查）
   * @returns 是否存在
   */
  async checkCustomerNameExists(customerName: string, excludeId?: number): Promise<boolean> {
    try {
      const params = excludeId ? { excludeId } : {}
      const response = await customerApiClient.get(`/api/Customer/check-name/${customerName}`, { params })
      const normalized = normalizeApiResult<any>(response)
      return (normalized.data as any) === true || response?.data === true
    } catch (error: unknown) {
      throw new Error(`检查客户名称失败: ${getErrorMessage(error)}`)
    }
  },

  /**
   * 检查统一社会信用代码是否存在
   * @param code 统一社会信用代码
   * @param excludeId 排除的客户ID（用于编辑时检查）
   * @returns 是否存在
   */
  async checkUnifiedSocialCreditCodeExists(code: string, excludeId?: number): Promise<boolean> {
    try {
      const params = excludeId ? { excludeId } : {}
      const response = await customerApiClient.get(`/api/Customer/check-code/${code}`, { params })
      const normalized = normalizeApiResult<any>(response)
      return (normalized.data as any) === true || response?.data === true
    } catch (error: unknown) {
      throw new Error(`检查统一社会信用代码失败: ${getErrorMessage(error)}`)
    }
  },

  /**
   * 生成客户编号
   * @returns 生成的客户编号
   */
  async generateCustomerNumber(): Promise<string> {
    try {
      const response = await customerApiClient.get('/api/Customer/generate-number')
      const normalized = normalizeApiResult<any>(response)
      return (normalized.data as any) ?? response?.data
    } catch (error: unknown) {
      throw new Error(`生成客户编号失败: ${getErrorMessage(error)}`)
    }
  }
}

// 导出默认实例
export default customerApi 